package com.beta.restapi.controller;

import com.beta.common.web.ContentType;
import com.beta.restapi.internal.Consts;
import com.beta.restapi.request.receiver.ReceiverRequest;
import com.beta.service.IReceiversService;
import com.beta.dto.user.ReceiverDto;
import com.beta.vo.user.ReceiverVO;
import io.swagger.annotations.Api;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by lichao on 2016/11/17.
 */
@Api(tags = "Receivers")
@RestController
@RequestMapping(Consts.API_PATH_PREFIX + Consts.Resource.RECEIVERS)
public class ReceiverController extends BaseController {

    @Autowired
    private IReceiversService receiversService;
    @Autowired
    private MapperFacade beanMapper;

    @GetMapping(value = "", produces = {ContentType.JSON})
    public Object getReceivers(@RequestHeader(Consts.HEADER_AUTH_KEY) String token) {
        List<ReceiverDto> receivers = receiversService.getReceiversByUserId(getCurrentUserId());
        return ok(beanMapper.mapAsList(receivers, ReceiverVO.class));
    }

    @PostMapping(value = {"", "/save_address"}, produces = {ContentType.JSON})
    public Object addReceiver(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                              @RequestBody ReceiverRequest receiverRequest) {
        ReceiverVO receiver = receiverRequest.getReceiver();
        return ok(receiversService.addReceiver(getCurrentUserId(), beanMapper.map(receiver, ReceiverDto.class)));
    }

    @PatchMapping(value = {"/{receiverId}", "/update_address/{receiverId}"}, produces = {ContentType.JSON})
    public Object updateReceiver(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                                 @PathVariable("receiverId") Integer receiverId,
                                 @RequestBody ReceiverRequest receiverRequest) {
        ReceiverVO receiverVO = receiverRequest.getReceiver();
        return ok(receiversService.updateReceiver(receiverId, beanMapper.map(receiverVO, ReceiverDto.class)));
    }

    @DeleteMapping(value = "/{receiverId}", produces = {ContentType.JSON})
    public Object deleteReceiver(@RequestHeader(Consts.HEADER_AUTH_KEY) String token,
                                 @PathVariable("receiverId") Integer receiverId) {
        receiversService.deleteReceiver(receiverId);
        return ok();
    }

}
